﻿#include "client/clientthread.h"
#include "client/clientwindow.h"
#include "valdefs.h"
#include <cstdio>
#include <QDebug>
#include <QApplication>
#if WIN32
#include <winsock2.h>
#else
#include <cstdio>
#include <iostream>
#include <cstring>
#include <sys/fcntl.h>
#include <sys/socket.h>
#include <unistd.h>
#include <netinet/in.h>
#include <errno.h>
#include <sys/types.h>
#include <arpa/inet.h>
#endif
#include "utils.h"

ClientThread::ClientThread(ClientWindow *cw, std::string pubkey, std::string prikey, QObject *parent) : QThread(parent){
    pubkey_ = pubkey;
    prikey_ = prikey;
    should_keep_running_ = true;
    cw_ = cw;
    should_send_ = false;
    send_buf_ = "";
    is_connected_with_server_ = false;
    connect(QCoreApplication::instance(), &QCoreApplication::destroyed, this, &ClientThread::OnAppClose);
    connect(this, &ClientThread::SignalSendMessage, this, &ClientThread::OnSendMessage);
    mtx_ = new QMutex;
}

void ClientThread::OnSendMessage(const char* msg){
    while(is_send_complete_);
    mtx_->lock();
    is_send_complete_ = false;
    should_send_ = true;
    send_buf_ = msg;
    mtx_->unlock();
}

void ClientThread::OnAppClose(){
    closesocket(sock_cache_);
#if WIN32
    WSACleanup();
#endif
}

void ClientThread::run(void){
    unsigned int client_socket_fd;
#if WIN32
    unsigned short      sock_version;
    struct WSAData      wsa_data;
    sock_version = MAKEWORD(2, 2);
    if(WSAStartup(sock_version, &wsa_data)!=0) {
        emit cw_->SignalShowSysMessage("WSA启动失败！");
    }
#endif
    this->sock_cache_ = client_socket_fd;

    while(should_keep_running_){
        //TODO
    }

    closesocket(client_socket_fd);
#if WIN32
    WSACleanup();
#endif
}

void ClientThread::OnReconfigureNetwork(int local_port, const char* server_ip, int server_port, int local_id, int target_port){
    this->terminate();
    this->should_keep_running_ = false;
    this->should_send_ = false;
    this->is_send_complete_ = true;
    this->local_port_ = local_port;
    this->server_port_ = server_port;
    this->server_ip_ = server_ip;
    this->start();
}

bool ClientThread::getIsConnected(){
    return is_connected_with_server_;
}
